<?php
/**
 * Created by PhpStorm.
 * User: tengjs
 * Date: 2020/11/3
 * Time: 7:37
 */

namespace App\Http\Controllers\Api\News;

use App\Admin\Models\ContentModel;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class NewsController extends BaseController
{
    /**
     * 新闻列表
     *
     * @return array
     */
    public function list()
    {
        // 参数校验
//        $validator = Validator::make($this->input(), [
//            'content_type' => [
//                'required',
//                'integer',
//                Rule::in([4])
//            ],
//        ], $this->messages(), $this->attributes());
//
//        if ($validator->fails()) {
//            return $this->failure($validator->errors()->first());
//        }

        $contentType = 4;
        $pageSize = $this->input('page_size', 10);

        $file = [
            'content_id', 'content_date', 'content_type', 'image_url', 'title_en as title', 'introduction_en as introduction'
        ];
        $res = ContentModel::select($file)->where('content_type', '=', $contentType)
            ->orderBy('content_date', 'desc')
            ->orderBy('content_id', 'desc')
            ->paginate($pageSize);
        $data = $this->buildPageList($res);
        foreach ($data['list'] as &$item) {
            $item['image_url'] = $this->buildImageUrl($item['image_url']);
        }
        unset($item);

        // 数据查询
        $result = [
            'code' => 0,
            'msg' => '数据获取成功！',
            'data' => $data
        ];

        return $this->success($result['data'], $result['msg'] ?: '数据获取成功！');
    }

    /**
     * 新闻详情
     *
     * @return array
     */
    public function detail()
    {
        // 参数校验
        $validator = Validator::make($this->input(), [
            'content_id' => 'required|integer|min:1',
        ], $this->messages(), $this->attributes());

        if ($validator->fails()) {
            return $this->failure($validator->errors()->first());
        }
        $contentId = $this->input('content_id');
        $file = [
            'content_id', 'content_date', 'content_type', 'image_url', 'title_en as title', 'content_en as content'
        ];
        $selectResult = ContentModel::select($file)->where('content_id', '=', $contentId)->first();
        $data = [];
        if (!empty($selectResult)) {
            $data = $selectResult->toArray();
            if (!empty($data['image_url'])) {
                $data['image_url'] = $this->buildImageUrl($data['image_url']);
            }
        }
        // 数据查询
        $result = [
            'code' => 0,
            'msg' => '数据获取成功！',
            'data' => $data
        ];
        return $this->success($result['data'], $result['msg'] ?: '数据获取成功！');
    }
}
